package com.cyk.comicforumjava.demos.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.MD5;
import com.cyk.comicforumjava.demos.base.ResponseResult;
import com.cyk.comicforumjava.demos.config.QiniuKey;
import com.cyk.comicforumjava.demos.dto.UserDto;
import com.cyk.comicforumjava.demos.enits.User;
import com.cyk.comicforumjava.demos.mapper.LoginMapper;
import com.cyk.comicforumjava.demos.mapper.ManageMapper;
import com.cyk.comicforumjava.demos.properties.JwtTokenProperties;
import com.cyk.comicforumjava.demos.service.LoginService;
import com.cyk.comicforumjava.demos.utils.AliyunSDK;
import com.cyk.comicforumjava.demos.utils.IdProcess;
import com.cyk.comicforumjava.demos.utils.JwtUtils;
import com.cyk.comicforumjava.demos.utils.ThreadLocalUtil;
import com.cyk.comicforumjava.demos.vo.LoginVo;
import com.qiniu.api.auth.AuthException;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
@Autowired
private LoginMapper loginMapper;
@Autowired
private JwtTokenProperties jwtTokenProperties;
@Autowired
private ManageMapper manageMapper;
    @Override
    public ResponseResult<LoginVo> login(UserDto userDto) {
        User user = loginMapper.selectByUsername(userDto.getUsername());
        if(user==null){
            return ResponseResult.error("用户名不存在");
        }else if(!user.getPassword().equals(MD5.create().digestHex16(userDto.getPassword()))){
            return ResponseResult.error("用户名或密码错误");
        }
        LoginVo loginVo=new LoginVo();
        ConcurrentHashMap<String, Object> cmap = new ConcurrentHashMap<>();
        cmap.put("username",user.getUsername());
        cmap.put("id",user.getId());
        System.out.println(ThreadLocalUtil.get());
        loginVo.setId(user.getId());
        loginVo.setUsername(user.getUsername());
        loginVo.setToken(JwtUtils.createJWT(jwtTokenProperties.getSecretKey(),jwtTokenProperties.getTtl(),cmap));
        loginVo.setAvator(user.getAvator());
        if(manageMapper.selectManagerById(user.getId())!=null){
            loginVo.setRole("管理员");
        }else{
            loginVo.setRole("普通用户");

        }
        return ResponseResult.success(loginVo);
    }

    @Override
    public ResponseResult<String> register(UserDto userDto) {
       User newuser= loginMapper.selectByUsername(userDto.getUsername());
       User newUser1=loginMapper.selectByphone(userDto.getNumber());
       if(userDto.getNumber().length() != 11){
           return ResponseResult.error("手机号格式不正确");
        }
        else{
            if(newUser1!=null){
                return ResponseResult.error("手机号已使用过");
            }else{
                if(newuser!=null){
                    return ResponseResult.error("用户名已存在");
                }
                else{
                    User user=new User();
                    BeanUtil.copyProperties(userDto,user);
                    user.setId(IdProcess.generateUserId());
                    user.setPassword(MD5.create().digestHex16(userDto.getPassword()));
                    user.setUserTime(LocalDateTime.now());
                    loginMapper.insert(user);
                    return ResponseResult.success("注册成功");
                }
            }
        }




    }

    @Override
    public ResponseResult<User> getUser(UserDto userDto) {
        User user = loginMapper.selectByUserId(userDto.getId());
        return ResponseResult.success(user);
    }

    @Override
    public ResponseResult<String> getQiniuToken(UserDto userDto) throws AuthException, JSONException {
        String token= QiniuKey.upload();
        ResponseResult<String> result=ResponseResult.success(token);
        return result;
    }



    @Override
    public ResponseResult<String> changeAvater(User user) throws UnsupportedEncodingException {
        user.setAvator(QiniuKey.finalurl(user.getAvator()));
        loginMapper.updateUser(user);
        return ResponseResult.success("更新头像成功");
    }

    @Override
    public ResponseResult<String> updateSignature(User user) {
        try{
            loginMapper.updateUser(user);
            return ResponseResult.success("更新个性签名成功");
        }catch (Exception e){
            throw e;
        }


    }

    @Override
    public ResponseResult getUserList() {
        List<User> users = loginMapper.selecAll(null);
        return ResponseResult.success(users);
    }

    @Override
    public ResponseResult confirmCode(UserDto userDto) throws Exception {
        User user=loginMapper.selectByUsername(userDto.getUsername());
        String confirmCode=AliyunSDK.sendSMS(user.getNumber()+"");
        return ResponseResult.success(confirmCode);
    }

    @Override
    public ResponseResult changePassword(UserDto userDto) {
        User user=loginMapper.selectByUsername(userDto.getUsername());
        user.setPassword(MD5.create().digestHex16(userDto.getPassword()));
        loginMapper.updateUser(user);
        return null;
    }
}
